package com.tuoren.forward.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tuoren.forward.entity.Product;
import com.tuoren.forward.entity.dto.ProductDto;
import com.tuoren.forward.entity.req.ProductAddReq;
import com.tuoren.forward.entity.req.ProductSearchReq;
import com.tuoren.forward.mapper.ProductMapper;
import com.tuoren.forward.util.AccessTokenUtil;
import com.tuoren.forward.util.Result;
import com.tuoren.forward.util.ResultData;
import com.tuoren.forward.util.ResultPage;
import com.tuoren.forward.util.UUIDUtil;

import cn.hutool.core.util.RandomUtil;


@Service
public class ProductService {
	
	@Autowired
	ProductMapper productMapper;
	
	/**
	 * @title 查询产品
	 * @param req
	 * @return ResultPage<Product>
	 */
	public ResultPage<Product> search(ProductSearchReq req){
		Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
		ProductDto dto = new ProductDto();
		BeanUtils.copyProperties(req, dto);
		List<Product> products = productMapper.select(dto);
		return ResultPage.success(products,page.getTotal());
	}
	
	/**
	 * @title 列出产品
	 * @return ResultData<List<Product>>
	 */
	public ResultData<List<Product>> listAll(){
		List<Product> list = productMapper.selectAll();
		return ResultData.success(list);
	}
	
	/**
	 * @title 添加产品 
	 * @param req
	 * @return Result
	 */
	public Result add(ProductAddReq req) {
		String userId = AccessTokenUtil.getUserId();
		Date date = new Date();
		Product record = new Product();
		BeanUtils.copyProperties(req, record);
		String code = UUIDUtil.getUniqStr();
		String secret = RandomUtil.randomString(16);
		record.setId(code);
		record.setCode(code);
		record.setSecret(secret);
		record.setCreatetime(date);
		record.setCreator(userId);
		record.setTenantId(userId);
		productMapper.insertSelective(record);
		return Result.success();
	}
	
	/**
	 * @title 修改产品 
	 * @param req
	 * @return Result
	 */
	public Result edit(ProductAddReq req) {
		String userId = AccessTokenUtil.getUserId();
		Date date = new Date();
		Product record = new Product();
		BeanUtils.copyProperties(req, record);
		record.setModifier(userId);
		record.setModifytime(date);
		productMapper.updateByPrimaryKeySelective(record);
		return Result.success();
	}
	
	/**
	 * @title 删除产品 
	 * @param req
	 * @return Result
	 */
	public Result delete(String id) {
		productMapper.deleteByPrimaryKey(id);
		return Result.success();
	}

}
